package com.example.finalwork.lmpl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.finalwork.DAO.UserDAO;
import com.example.finalwork.DB.Constants;
import com.example.finalwork.DB.DataBaseHelper;
import com.example.finalwork.Entity.User;

import java.util.ArrayList;
import java.util.List;

public class UserDAOlmpl implements UserDAO {
    private final DataBaseHelper mDataBaseHelper;
    public UserDAOlmpl(Context context){
        mDataBaseHelper = new DataBaseHelper(context);
    }
    @Override
    public long addUser(User user) {
        SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
        ContentValues values = user2values(user);
        long result = db.insert(Constants.User_Table_Name,null,values);
        db.close();
        return result;
    }
    @Override
    public int updateUser(User user){
        SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
        ContentValues values = user2values(user);
        int result = db.update(Constants.User_Table_Name,values,"UserName=?",new String[]{user.getUserName()});
        db.close();
        return result;
    }

    @Override
    public List<User> GetAllUser() {
        List<User> users = new ArrayList<>();

        SQLiteDatabase db = mDataBaseHelper.getReadableDatabase();
        Cursor cursor = db.query(Constants.User_Table_Name,null,null,null,null,null,null,null);
        while(cursor.moveToNext())
        {
            User user = new User();

            String UserName = cursor.getString(cursor.getColumnIndex("UserName"));
            user.setUserName(UserName);

            String PassWord = cursor.getString(cursor.getColumnIndex("PassWord"));
            user.setPassWord(PassWord);

            users.add(user);
        }
        db.close();
        return users;
    }
    private ContentValues user2values(User user) {
        //添加数据
        ContentValues values = new ContentValues();
        values.put("UserName",user.getUserName());
        values.put("PassWord",user.getPassWord());
        return values;
    }
}
